package view;

import java.util.ArrayList;
import com.example.pruebapfi.R;
import controller.AlimentoController;
import dtos.AlimentoDTO;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("DefaultLocale")
public class ListarAlimentos extends ActionBarActivity {
	
	private EditText etSearch;
	private ListView lvAlimentos;

	private ArrayList<AlimentoDTO> mAlimentoArrayList = new ArrayList<AlimentoDTO>();
	private MyAdapter adapter1;


	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_listar_alimentos);
	    android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
        Header header=(Header) findViewById(R.id.header1);
		header.setTitle("Alimentos");
		header.setActivity(this,R.layout.overlay_view_listar_alimentos_help);
	    Bundle extras=getIntent().getExtras();
		String tipo=extras.getString("tipo");
	    initialize();
	    if(tipo.equals("categoria")){
			int idCategoria=extras.getInt("idCategoria");
			mAlimentoArrayList=AlimentoController.getInstance().obtenerAlimentosCategoria(getApplicationContext(),idCategoria);			
		}else{
			if(tipo.equals("ingesta")){
				mAlimentoArrayList=AlimentoController.getInstance().obtenerAlimentosIngesta(getApplicationContext());			
			}
			else{
				mAlimentoArrayList=AlimentoController.getInstance().obtenerAlimentos(getApplicationContext());
			}
		}
	    adapter1 = new MyAdapter(ListarAlimentos.this, mAlimentoArrayList);
	    lvAlimentos.setAdapter(adapter1);
	   
	    // Add Text Change Listener to EditText
	    etSearch.addTextChangedListener(new TextWatcher() {

	        @Override
	        public void onTextChanged(CharSequence s, int start, int before, int count) {
	            // Call back the Adapter with current character to Filter
	            adapter1.getFilter().filter(s.toString());
	        }

	        @Override
	        public void beforeTextChanged(CharSequence s, int start, int count,int after) {
	        }

	        @Override
	        public void afterTextChanged(Editable s) {
	        }
	    });
	}

	private void initialize() {
	    etSearch = (EditText) findViewById(R.id.etSearchAlimento);
	    lvAlimentos = (ListView)findViewById(R.id.lvAlimentos);
	}

	@Override
	protected void onResume() {
	    super.onResume();
	}


	// Adapter Class            
	public class MyAdapter extends BaseAdapter implements Filterable {

	private ArrayList<AlimentoDTO> mOriginalValues; // Original Values
	private ArrayList<AlimentoDTO> mDisplayedValues;    // Values to be displayed
	LayoutInflater inflater;

	public MyAdapter(Context context, ArrayList<AlimentoDTO> mAlimentoArrayList) {
	    this.mOriginalValues = mAlimentoArrayList;
	    this.mDisplayedValues = mAlimentoArrayList;
	    inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
	    return mDisplayedValues.size();
	}

	@Override
	public Object getItem(int position) {
	    return position;
	}

	@Override
	public long getItemId(int position) {
	    return position;
	}

	private class ViewHolder {
	    LinearLayout llContainer;
	    TextView alimentoNombre;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

	    ViewHolder holder = null;

	    if (convertView == null) {

	        holder = new ViewHolder();
	        convertView = inflater.inflate(R.layout.row_alimento, null);
	        holder.llContainer = (LinearLayout)convertView.findViewById(R.id.llContainerAlimento);
	        holder.alimentoNombre = (TextView) convertView.findViewById(R.id.alimentoNombre);
	        convertView.setTag(holder);
	    } else {
	        holder = (ViewHolder) convertView.getTag();
	    }
	    holder.alimentoNombre.setText(mDisplayedValues.get(position).getNombre());

	    holder.llContainer.setOnClickListener(new OnClickListener() {

	        public void onClick(View v) {
	    	    Bundle extras=getIntent().getExtras();
	    		String tipo=extras.getString("tipo");
	        	 if(tipo.equals("ingesta")){	     					
	     			        Intent intent= new Intent(getApplicationContext(),IngresarIngesta.class);
	     			        intent.putExtra("alimento", mDisplayedValues.get(position).getId());
	     					startActivity(intent);
	     		}
	     			
	     	    
	        }
	    });

	    return convertView;
	}

	@Override
	public Filter getFilter() {
	    Filter filter = new Filter() {

	        @SuppressWarnings("unchecked")
	        @Override
	        protected void publishResults(CharSequence constraint,FilterResults results) {

	            mDisplayedValues = (ArrayList<AlimentoDTO>) results.values; // has the filtered values
	            notifyDataSetChanged();  // notifies the data with new filtered values
	        }

	        @Override
	        protected FilterResults performFiltering(CharSequence constraint) {
	            FilterResults results = new FilterResults();        // Holds the results of a filtering operation in values
	            ArrayList<AlimentoDTO> FilteredArrList = new ArrayList<AlimentoDTO>();

	            if (mOriginalValues == null) {
	                mOriginalValues = new ArrayList<AlimentoDTO>(mDisplayedValues); // saves the original data in mOriginalValues
	            }

	            /********
	             * 
	             *  If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
	             *  else does the Filtering and returns FilteredArrList(Filtered)  
	             *
	             ********/
	            if (constraint == null || constraint.length() == 0) {

	                // set the Original result to return  
	                results.count = mOriginalValues.size();
	                results.values = mOriginalValues;
	            } else {
	                constraint = constraint.toString().toLowerCase();
	                for (int i = 0; i < mOriginalValues.size(); i++) {
	                    String data = mOriginalValues.get(i).getNombre();
	                    if (data.toLowerCase().startsWith(constraint.toString())) {
	                        FilteredArrList.add(new AlimentoDTO(mOriginalValues.get(i).getNombre(),mOriginalValues.get(i).getId()));
	                    }
	                }
	                // set the Filtered result to return
	                results.count = FilteredArrList.size();
	                results.values = FilteredArrList;
	            }
	            return results;
	        }
	    };
	    return filter;
	}
	}
}
